package service

import (
	"fmt"
	"newsletter-subs/pkg/mapper"
	"newsletter-subs/pkg/model"
	"time"
)

func GetSubscriptions() (results model.Results) {
	//TODO test mongo only
	return MongoGetSubscriptions()

	// subs := []model.Subscription{}
	// subs = mapper.Subscription.FindAll()

	// for _, sub := range subs {
	// 	results.Data = append(results.Data, sub)
	// }
	// results.Count = len(subs)
	// return
}

func CreateSubscription(subs *model.MSubscription) (result model.Result) {
	//TODO test mongo only
	return MongoCreateSubscription(subs)

	// subs.CreatedAt = time.Now()
	// id, _ := mapper.Subscription.Create(subs)

	// subscription := mapper.Subscription.FindById(id)
	// result.Count = 1
	// result.Data = subscription
	// return
}

func MongoGetSubscriptions() (results model.Results) {
	subs := []model.MSubscription{}
	var err error
	if subs, err = mapper.MSubscription.FindAll(); err != nil {
		return
	}

	for _, sub := range subs {
		results.Data = append(results.Data, sub)
	}
	results.Count = len(subs)
	return
}

func MongoCreateSubscription(subs *model.MSubscription) (result model.Result) {
	var err error
	subs.CreatedAt = time.Now()
	if err = mapper.MSubscription.Create(subs); err != nil {
		return
	}

	fmt.Println("Create subscription:")
	result.Count = 1
	result.Data = subs
	return
}

func UpdateSubscription(id string, subs *model.MSubscription) (result model.Result) {
	subs.UpdatedAt = time.Now()
	// mapper.Subscription.Update(subs)
	// subscription := mapper.Subscription.FindById(subs.Id)
	mapper.MSubscription.Update(subs)
	subscription, _ := mapper.MSubscription.Find(id)
	result.Count = 1
	result.Data = subscription
	return
}

func GetOneSubscription(id string) (result model.Result) {

	// subscription := mapper.Subscription.FindById(id)
	subscription, _ := mapper.MSubscription.Find(id)
	result.Count = 1
	result.Data = subscription
	return
}

func DeleteSubscription(id string) {
	fmt.Println("Delete subscription:", id)
	// mapper.Subscription.Delete(id)
	mapper.MSubscription.Delete(id)
}
